using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyControls.DataSources.CompositeHierarchicalDataSource {
    /// <summary>
    /// A view on the <see cref="CompositeHierarchicalDataSource"/>.
    /// </summary>
    public class CompositeHierarchicalDataSourceView : HierarchicalDataSourceView {
        // TODO: implement data source change events
        private CompositeHierarchicalDataSource _owner;
        private string _viewPath;

        internal CompositeHierarchicalDataSourceView(CompositeHierarchicalDataSource owner, string viewPath) {
            _owner = owner;
            _viewPath = (viewPath == null) ? String.Empty : viewPath;
        }

        public override IHierarchicalEnumerable Select() {
            if (_owner.DataSet.Tables.Count == 0) {
                return new CompositeHierarchicalEnumerable(new DataRow[] { });
            }
            int slashPos = _viewPath.IndexOf('/');
            string tableNameAndSpace = (slashPos == -1) ? _viewPath : _viewPath.Substring(0, slashPos);
            int columnPos = tableNameAndSpace.IndexOf(':');
            string tableName = (columnPos == -1 || columnPos == tableNameAndSpace.Length - 1) ?
                tableNameAndSpace :
                tableNameAndSpace.Substring(columnPos + 1);
            string nameSpace = (columnPos <= 0) ?
                String.Empty :
                tableNameAndSpace.Substring(0, columnPos);
            DataTable table = _owner.DataSet.Tables[tableName, nameSpace];
            if (table == null) return new CompositeHierarchicalEnumerable(new DataRow[] { });

            if (slashPos != -1 && slashPos + 1 < _viewPath.Length) {
                return new CompositeHierarchicalEnumerable(table.Select(_viewPath.Substring(slashPos + 1)));
            }

            return new CompositeHierarchicalEnumerable(table.Select());
        }
    }
}
